/*
 * Copyright (c) 2011 Joe Kopena <tjkopena@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
*/

package com.rocketshipgames.haxe.sfx;

import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.Event;

import com.rocketshipgames.haxe.AssetCache;

enum Replay {
  Reset;
  Continue;
}

class Sfx {

  private var _sound:Sound;
  private var _loop:Bool;
  private var _channel:SoundChannel;
  private var _replay:Replay;

  public var playing:Bool;

  public function new(path:String, ?replay:Replay):Void
  {

    _sound = AssetCache.instance().getSound(path);
    if (_sound == null) {
      trace("ERROR: Null sound for '" + path + "'");
      return;
    }

    if (replay == null)
      _replay = Continue;
    else
      _replay = replay;

    _loop = false;

    _channel = null;
    playing = false;

    // end function new
  }

  //--------------------------------------------------------------------
  public function play(?loop:Bool=false):Void
  {
    if (_channel != null) {
      if (_replay == Continue) {
	return;
      } else {
	_channel.stop();
      }
    }

    _loop = loop;
    _channel = _sound.play();
    _channel.addEventListener(Event.SOUND_COMPLETE, onComplete);
    playing = true;
    // end function play
  }

  public function stop():Void
  {
    playing = false;
    _loop = false;
    if (_channel != null)
      _channel.stop();
    _channel = null;
    // end function stop
  }


  //--------------------------------------------------------------------
  private function onComplete(e:Event):Void
  {
    _channel = null;
    playing = false;
    if (_loop)
      play(true);
    // end function onComplete
  }

  // end class Sfx
}
